package com.yt.sys.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.common.utils.CustomizeUtil;
import com.yt.sys.models.bo.LoginRequest;
import com.yt.sys.models.vo.AddAccountRequest;
import com.yt.sys.models.vo.UserInfoRequest;
import com.yt.sys.models.vo.UserInfoVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.sys.models.service.ILoginInfoService;
import com.yt.sys.models.service.ISysPermissionService;
import com.yt.sys.models.service.ISysRolePermissionService;
import com.yt.sys.models.service.ISysRoleService;
import com.yt.sys.models.service.ISysUserRoleService;
import com.yt.sys.models.service.ISysUserService;
import com.yt.sys.models.bo.LoginInfoSaveBO;
import com.yt.sys.models.bo.LoginInfoBO;
import com.yt.sys.models.dto.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 登录信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:21:03
 */

@RestController
@RequestMapping("/api/loginInfo")
@Slf4j
@Api(value = "LoginInfoApiController",tags = "登录信息Api接口")
public class LoginInfoApiController {

    @DubboReference
    private ILoginInfoService loginInfoService;
    
    @DubboReference
    private ISysUserService sysUserService;
    
    @DubboReference
    private ISysRoleService sysRoleService;
    
    @DubboReference
    private ISysUserRoleService sysUserRoleService;
    
    @DubboReference
    private ISysRolePermissionService sysRolePermissionService;
    
    @DubboReference
    private ISysPermissionService sysPermissionService;

    @PostMapping("/getUserInfo")
    @ApiOperation(value = "根据用户ID获取用户的详细信息", notes = "根据用户ID获取用户的详细信息，包括用户基本信息、角色列表和权限列表")
    public Result<UserInfoVO> getUserInfo(@RequestParam(required = false) Long userId, 
                                          @RequestBody(required = false) UserInfoRequest request) {
        // 参数校验，支持两种方式传递userId
        Long id = null;
        if (userId != null) {
            // 通过@RequestParam方式传递userId
            id = userId;
        } else if (request != null && request.getUserId() != null) {
            // 通过@RequestBody方式传递userId
            id = request.getUserId();
        } else {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID不能为空");
        }
        
        UserInfoVO userInfoVO = new UserInfoVO();
        
        // 获取用户基本信息
        SysUserDTO user = sysUserService.selectById(id);
        if (user == null) {
            return new Result<>(CodeEnum.FAIL_100003.getCode(), "用户不存在");
        }
        userInfoVO.setUser(user);
        
        // 获取用户角色列表
        Wrapper<SysUserRoleDTO> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("user_id", id);
        List<SysUserRoleDTO> userRoles = sysUserRoleService.selectList(userRoleWrapper);
        
        List<SysRoleDTO> roles = new ArrayList<>();
        if (userRoles != null && !userRoles.isEmpty()) {
            List<Long> roleIds = userRoles.stream()
                    .map(SysUserRoleDTO::getRoleId)
                    .collect(Collectors.toList());
            
            Wrapper<SysRoleDTO> roleWrapper = new EntityWrapper<>();
            roleWrapper.in("id", roleIds);
            roleWrapper.eq("status", 1); // 只查询启用状态的角色
            roles = sysRoleService.selectList(roleWrapper);
        }
        userInfoVO.setRoles(roles);
        
        // 获取用户权限列表
        List<SysPermissionDTO> permissions = new ArrayList<>();
        if (userRoles != null && !userRoles.isEmpty()) {
            List<Long> roleIds = userRoles.stream()
                    .map(SysUserRoleDTO::getRoleId)
                    .collect(Collectors.toList());
            
            // 查询角色权限关联信息
            Wrapper<SysRolePermissionDTO> rolePermissionWrapper = new EntityWrapper<>();
            rolePermissionWrapper.in("role_id", roleIds);
            List<SysRolePermissionDTO> rolePermissions = sysRolePermissionService.selectList(rolePermissionWrapper);
            
            if (rolePermissions != null && !rolePermissions.isEmpty()) {
                List<Long> permissionIds = rolePermissions.stream()
                        .map(SysRolePermissionDTO::getPermissionId)
                        .collect(Collectors.toList());
                
                // 查询权限信息
                Wrapper<SysPermissionDTO> permissionWrapper = new EntityWrapper<>();
                permissionWrapper.in("id", permissionIds);
                permissionWrapper.eq("status", 1); // 只查询启用状态的权限
                permissions = sysPermissionService.selectList(permissionWrapper);
            }
        }
        userInfoVO.setPermissions(permissions);
        
        return new Result<>(CodeEnum.SUCCESS.getCode(), "获取用户信息成功", userInfoVO);
    }

    @PostMapping("/getUserMenuPermissions") 
    @ApiOperation(value = "获取用户菜单权限", notes = "根据用户角色获取用户有权限访问的菜单项")
    public Result<List<String>> getUserMenuPermissions(@RequestParam Long userId) {
        // 参数校验
        if (userId == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID不能为空");
        }
        
        // 获取用户角色列表
        Wrapper<SysUserRoleDTO> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("user_id", userId);
        List<SysUserRoleDTO> userRoles = sysUserRoleService.selectList(userRoleWrapper);
        
        List<String> menuUrls = new ArrayList<>();
        if (userRoles != null && !userRoles.isEmpty()) {
            // 提取角色ID列表
            List<Long> roleIds = userRoles.stream()
                    .map(SysUserRoleDTO::getRoleId)
                    .collect(Collectors.toList());
            
            // 查询角色权限关联信息
            Wrapper<SysRolePermissionDTO> rolePermissionWrapper = new EntityWrapper<>();
            rolePermissionWrapper.in("role_id", roleIds);
            List<SysRolePermissionDTO> rolePermissions = sysRolePermissionService.selectList(rolePermissionWrapper);
            
            if (rolePermissions != null && !rolePermissions.isEmpty()) {
                // 提取权限ID列表
                List<Long> permissionIds = rolePermissions.stream()
                        .map(SysRolePermissionDTO::getPermissionId)
                        .collect(Collectors.toList());
                
                // 查询菜单类型的权限信息
                Wrapper<SysPermissionDTO> permissionWrapper = new EntityWrapper<>();
                permissionWrapper.in("id", permissionIds);
                permissionWrapper.eq("type", 0); // 0表示菜单类型权限
                permissionWrapper.eq("status", 1); // 只查询启用状态的权限
                List<SysPermissionDTO> menuPermissions = sysPermissionService.selectList(permissionWrapper);
                
                // 提取菜单路径
                menuUrls = menuPermissions.stream()
                        .map(SysPermissionDTO::getUrl)
                        .filter(url -> url != null && !url.isEmpty())
                        .collect(Collectors.toList());
            }
        }
        
        return new Result<>(CodeEnum.SUCCESS.getCode(), "获取用户菜单权限成功", menuUrls);
    }

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    public Result<LoginInfoDTO> login(@RequestBody LoginRequest loginRequest) {
        // 参数校验
        if (loginRequest.getAccount() == null || loginRequest.getAccount().trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "账号不能为空");
        }
        
        if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "密码不能为空");
        }
        
        // 查询用户信息
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("account", loginRequest.getAccount());
        wrapper.eq("status", 1); // 只查询启用状态的账号
        
        List<LoginInfoDTO> loginInfoList = loginInfoService.selectList(wrapper);
        
        // 判断账号是否存在
        if (loginInfoList == null || loginInfoList.isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100003.getCode(), "账号不存在或已被锁定");
        }
        
        LoginInfoDTO loginInfo = loginInfoList.get(0);
        
        // 验证密码（使用加盐MD5加密后比较）
        String encryptedPassword = DigestUtils.md5DigestAsHex((loginRequest.getPassword() + loginInfo.getSalt()).getBytes());
        if (!encryptedPassword.equals(loginInfo.getPassword())) {
            return new Result<>(CodeEnum.FAIL_100004.getCode(), "密码错误");
        }
        
        // 登录成功，返回用户信息（不包含密码）
        loginInfo.setPassword(null);
        loginInfo.setSalt(null);
        
        return new Result<>(CodeEnum.SUCCESS.getCode(), "登录成功", loginInfo);
    }

    @PostMapping("/addAccount")
    @ApiOperation(value = "添加账号", notes = "为指定用户添加登录账号")
    public Result<Void> addAccount(@RequestBody AddAccountRequest request) {
        // 参数校验
        if (request == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "请求参数不能为空");
        }
        
        if (request.getUserId() == null) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "用户ID不能为空");
        }
        
        if (CustomizeUtil.strIsNull(request.getAccount())) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "账号不能为空");
        }
        
        if (CustomizeUtil.strIsNull(request.getPassword())) {
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "密码不能为空");
        }
        
        // 验证账号是否已存在
        Wrapper<LoginInfoDTO> checkWrapper = new EntityWrapper<>();
        checkWrapper.eq("account", request.getAccount());
        int count = loginInfoService.selectCount(checkWrapper);
        if (count > 0) {
            return new Result<>(CodeEnum.FAIL_USER_200002.getCode(), "账号已存在");
        }
        
        // 创建账号信息
        LoginInfoSaveBO saveBO = new LoginInfoSaveBO();
        saveBO.setUserId(String.valueOf(request.getUserId()));
        saveBO.setAccount(request.getAccount());
        
        // 对密码进行MD5加盐加密
        String salt = UUID.randomUUID().toString().replace("-", "").substring(0, 6);
        String encryptedPassword = DigestUtils.md5DigestAsHex((request.getPassword() + salt).getBytes());
        saveBO.setPassword(encryptedPassword);
        saveBO.setSalt(salt);
        saveBO.setStatus(1); // 默认启用状态
        
        // 设置创建时间和更新时间
        Date now = new Date();
        saveBO.setCreateTime(now);
        saveBO.setUpdateTime(now);
        
        // 保存账号信息
        boolean result = loginInfoService.add(saveBO);
        if (result) {
            return new Result<>(CodeEnum.SUCCESS.getCode(), "账号创建成功");
        } else {
            return new Result<>(CodeEnum.FAIL_100007.getCode(), "账号创建失败");
        }
    }

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<LoginInfoDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        LoginInfoDTO dto = loginInfoService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "登录信息列表",notes = "登录信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<LoginInfoDTO>> queryPageList(LoginInfoBO bo){
        Wrapper<LoginInfoDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<LoginInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = loginInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }
}